<template>
    <Layout>
      <Spin fix v-if="isSpin">
        <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
        <div>正在生成导出文件，请稍后</div>
      </Spin>
        <Form ref="form1" :model="form1" :label-width="120">
            <Row class="query-form" style="padding-top: 15px">
              <Col span="8">
                <FormItem label="报送单位：" prop="reportOrgId">
                  <company-select v-model="form1.orgName" class="query-form-el"></company-select>
                </FormItem>
              </Col>
              <Col span="8">
                <FormItem label="二级集团：" prop="twoLevelOrgId">
                  <two-level-org org-code class="query-form-el" v-model="form1.twoLevelOrgId"></two-level-org>
                </FormItem>
              </Col>

              <Col span="8" v-show="switchFlag">
                <FormItem label="应急事件名称：" prop="emergencyName">
                  <Input class="query-form-el" type="text" v-model="form1.emergencyName" style="width: 100%;"></Input>
                </FormItem>
              </Col>

              <Col span="8" v-show="!switchFlag">
                <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
                <Button @click="reset" class="ivu-btn-reset">重置</Button>
                <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
              </Col>
            </Row>
          <Row v-show="switchFlag" class="query-form">
            <Col span="8">
              <FormItem label="应急事件等级：" prop="eLevelId">
                <Select v-model="form1.eLevelIdsQuery" multiple :max-tag-count="1" @on-change="selectElevelIds"
                        class="query-form-el">
                  <Option v-for="item in eLevelList" :value="item.codingCodeId"
                          :key="item.codingCodeId">{{ item.codingName }}
                  </Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="8">
              <FormItem label="是否演练事件：" prop="trainEvent">
                <Select v-model="form1.trainEventQuery" multiple :max-tag-count="2" @on-change="selecTrainEvent"
                        class="query-form-el">
                  <Option v-for="item in trainEventList" :value="item.value" :key="item.value">{{
                      item.lable
                    }}
                  </Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="8">
              <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
              <Button @click="reset" class="ivu-btn-reset">重置</Button>
              <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
            </Col>
          </Row>
          <Row class="query-form">
            <Col span="24">
              <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
              <!--<Button size="large"  class="ivu-btn-delete" icon="md-trash" @click="batDelete">删除</Button>-->
              <Button type="primary" class="ivu-btn-add"   icon="md-cloud-download"  @click="downloadExcel">导出</Button>

            </Col>
          </Row>
        </Form>

        <Table ref='table' :height="tableHeight" :loading="loading" size="small" no-data-text="没有查询到相关数据!" @on-sort-change="querySort"
               @on-selection-change='getSelectRows'
               border :columns="columns1" :data="dataTable">
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24">
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
                      @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
                      show-total show-sizer show-elevator/>
            </Col>
        </Row>
        <Modal :title="add?'应急事件信息新增':'应急事件信息修改'" :transfer=false v-model="model1" :width=600 @on-cancel="handleCancel">
            <Row>
                <Col span="24">
                    <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom" label-position="top">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="7">
                                <FormItem label="应急事件名称：" prop="emergencyName">
                                    <Input type="text" v-model="form1datacopy.emergencyName"></Input>
                                </FormItem>
                            </Col>
                            <Col span="7">
                                <FormItem label="报送单位：" prop="reportOrgId">
                                    <cascaderDom class="query-form-el" style="padding-top: 4px" ref="carOrg"
                                                 @setOrgInfo="setCurrentOrgId" @setOrgName="setCurrentOrgName"
                                                 :currentOrgId="form1datacopy.reportOrgId "
                                                 :currentOrgName="form1datacopy.orgName" :orgTree="true"></cascaderDom>
                                </FormItem>
                            </Col>
                            <Col span="7">
                                <FormItem label="报送人：" prop="reportorId">
                                    <Select
                                            v-model="form1datacopy.reportorId"
                                            filterable
                                            :remote-method="remoteMethod1"
                                            :loading="loading1">
                                        <Option v-for="(option, index) in options1" :value="option.userId"
                                                :label="option.userName" :key="index">
                                            <span>{{option.userName}}</span>
                                            <span style="float:right;color:#ccc">{{option.orgInfo.orgName}}</span>
                                        </Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>

                        <Row type="flex" justify="space-around" class="code-row-bg">

                            <Col span="7">
                                <FormItem label="坐标名称：" prop="axisName">
                                    <Input icon="ios-search" placeholder="Select..." @on-click="openPointModal()"
                                           v-model="form1datacopy.axisName"></Input>
                                </FormItem>
                            </Col>
                            <Col span="7">
                                <FormItem label="发生地点：" prop="emergencyLocation">
                                    <Input type="text" v-model="form1datacopy.emergencyLocation"></Input>
                                </FormItem>
                            </Col>
                            <Col span="7">
                                <FormItem label="联系方式：" prop="cellPhone">
                                    <Input type="text" v-model="form1datacopy.cellPhone"></Input>
                                </FormItem>
                            </Col>

                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">

                            <Col span="7">
                                <FormItem label="事件发生时间：" prop="occurDate">
                                    <DatePicker v-model="form1datacopy.occurDate" type="date"
                                                placeholder="请输入"></DatePicker>
                                </FormItem>
                            </Col>
                            <Col span="7">
                                <FormItem label="上报时间：" prop="reportDate">
                                    <DatePicker v-model="form1datacopy.reportDate" type="date"
                                                placeholder="请输入"></DatePicker>
                                </FormItem>
                            </Col>
                            <Col span="7">
                                <FormItem label="损失金额：" prop="amountLoss">
                                    <Input number v-model="form1datacopy.amountLoss"></Input>
                                </FormItem>
                            </Col>

                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">

                            <Col span="7">
                                <FormItem label="应急事件等级：" prop="eLevelId">
                                    <Select filterable v-model="form1datacopy.eLevelId">
                                        <Option v-for="item in eLevelList" :value="item.codingCodeId"
                                                :key="item.codingCodeId">{{ item.codingName }}
                                        </Option>
                                    </Select>
                                </FormItem>
                            </Col>
                          <!--                            <Col span="7">
                                                          <FormItem label="应急事件类型：" prop="eTypeId">
                                                              <Select filterable v-model="form1datacopy.eTypeId">
                                                                  <Option v-for="item in eTypeList" :value="item.codingCodeId"
                                                                          :key="item.codingCodeId">{{ item.codingName }}
                                                                  </Option>
                                                              </Select>
                                                          </FormItem>
                                                      </Col>-->
                          <Col span="7">
                            <FormItem label="是否演练事件：" prop="trainEvent">
                              <Select filterable v-model="form1datacopy.trainEvent">
                                <Option v-for="item in trainEventList" :value="item.value" :key="item.value">{{
                                    item.lable
                                  }}
                                </Option>
                              </Select>
                            </FormItem>
                          </Col>
                          <Col span="7">
                            <FormItem label="死亡失踪人数：" prop="missingDeath">
                              <Input type="text" v-model="form1datacopy.missingDeath"></Input>
                            </FormItem>
                          </Col>

                        </Row>
                      <Row type="flex" justify="space-around" class="code-row-bg">


                        <Col span="7">
                          <FormItem label="重伤人数：" prop="severeWound">
                            <Input type="text" v-model="form1datacopy.severeWound"></Input>
                          </FormItem>
                        </Col>
                        <Col span="7">
                          <FormItem label="轻伤人数：" prop="minorWound">
                            <Input type="text" v-model="form1datacopy.minorWound"></Input>
                          </FormItem>
                        </Col>
                        <Col span="7">

                        </Col>

                      </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="事件附件文件：">
                                    <div style="width: 100%">
                                        <Upload ref="upload"
                                                :before-upload="beforeUpload"
                                                :show-upload-list="true"
                                                :max-size="10240"
                                                multiple
                                                type="drag"
                                                :action="fileUrl">
                                            <div style="padding: 20px">
                                                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                                <p>点击将文件拖拽到这里上传</p>
                                                <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                                            </div>
                                        </Upload>
                                    </div>

                                    <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                                        <a @click="downloadFile(form1datacopy.emergencyId,item)">{{ item.fileName }}</a>
                                        <Button type="text" icon="md-trash" @click="remove1(item.id)"
                                                style="margin-left: 5px;margin-bottom: 3px"/>
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="应急事件描述：" prop="emergencyDesc">
                                    <Input v-model="form1datacopy.emergencyDesc" type="textarea" :rows="2"/>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">

                            <Col span="23">
                                <FormItem label="事发原因：" prop="emergencyCause">
                                    <Input v-model="form1datacopy.emergencyCause" type="textarea" :rows="2"/>
                                </FormItem>
                            </Col>


                        </Row>

                        <Row type="flex" justify="space-around" class="code-row-bg">

                            <Col span="23">
                                <FormItem label="备注信息：" prop="notes">
                                    <Input v-model="form1datacopy.notes" type="textarea" :rows="2"/>
                                </FormItem>
                            </Col>


                        </Row>
                        <!-- <Row type="flex" justify="center" class="code-row-bg">
                             <Col span="23" >
                                 <FormItem>
                                     <Button type="primary"  class='ivu-btn-save' :loading="buttonLoading" @click="submit('form1datacopy')" >确定</Button>
                                     <Button type="primary"  class='ivu-btn-cancel' @click="handleCancel" >取消</Button>
                                 </FormItem>
                             </Col>
                         </Row>-->
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' :loading="buttonLoading" @click="submit('form1datacopy')">
                    确定
                </Button>
                <Button type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
            </div>
        </Modal>
        <Modal title="应急事件信息" class="modal-view-detail" :transfer=false v-model="model2" :width=800>
            <Row>
                <Col span="24">
                    <Form :model="form1datacopy" :label-width="160">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="应急事件名称：" prop="emergencyName">
                                    {{form1datacopy.emergencyName}}
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="报送单位：" prop="orgName">
                                    {{form1datacopy.orgName}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="报送人：" prop="userName">
                                    {{form1datacopy.userName}}
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="坐标名称：" prop="axisName">
                                    {{form1datacopy.axisName}}
                                </FormItem>
                            </Col>

                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="发生地点：" prop="emergencyLocation">
                                    {{form1datacopy.emergencyLocation}}
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="联系方式：" prop="cellPhone">
                                    {{form1datacopy.cellPhone}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="事件发生时间：" prop="occurDate">
                                    {{formatDate(new Date(this.form1datacopy.occurDate), 'yyyy-MM-dd')}}
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="上报时间：" prop="reportDate">
                                    {{formatDate(new Date(this.form1datacopy.reportDate), 'yyyy-MM-dd')}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="损失金额：" prop="amountLoss">
                                    {{form1datacopy.amountLoss}}
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="应急事件等级：" prop="eLevelName">
                                    {{form1datacopy.eLevelName}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                          <!--                            <Col span="11">-->
                          <!--                                <FormItem label="应急事件类型：" prop="eTypeName">-->
                          <!--                                    {{form1datacopy.eTypeName}}-->
                          <!--                                </FormItem>-->
                          <!--                            </Col>-->
                          <Col span="11">
                            <FormItem label="是否演练事件：" prop="trainEvent">
                              {{ form1datacopy.trainEvent === '1' ? '真实事件' : '演练事件' }}
                            </FormItem>
                          </Col>
                          <Col span="11">
                            <FormItem label="死亡失踪人数：" prop="missingDeath">
                              {{ form1datacopy.missingDeath }}
                            </FormItem>
                          </Col>
                        </Row>
                      <Row type="flex" justify="space-around" class="code-row-bg">

                        <Col span="11">
                          <FormItem label="重伤人数：" prop="severeWound">
                            {{ form1datacopy.severeWound }}
                          </FormItem>
                        </Col>
                        <Col span="11">
                          <FormItem label="轻伤人数：" prop="minorWound">
                            {{ form1datacopy.minorWound }}
                          </FormItem>
                        </Col>
                      </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="事件附件文件：">
                                    <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                                        <a @click="downloadFile(form1datacopy.emergencyId,item)">{{ item.fileName }}</a>
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="应急事件描述：" prop="emergencyDesc ">
                                    {{form1datacopy.emergencyDesc}}
                                </FormItem>
                            </Col>

                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="事发原因：" prop="emergencyCause ">
                                    {{form1datacopy.emergencyCause}}
                                </FormItem>
                            </Col>

                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="备注：" prop="notes ">
                                    {{form1datacopy.notes }}
                                </FormItem>
                            </Col>

                        </Row>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
            </div>
        </Modal>
        <Modal :transfer=false footer-hide v-model="selectPointModal" :width=800
               style="display: flex; align-items: center; justify-content: center;">
            <PointForSelect @getSelectPointData="getSelectPointData"></PointForSelect>
        </Modal>
    </Layout>
</template>

<script>
import {Api} from '../../../../api'
import cascaderDom from "../../../../components/cascader-dom.vue"
import PointForSelect from '../storage/sitePointSelect.vue'
import {sessionStorage} from '../../../../common/cacheUtils.js';
import {formatDate} from "@/tools";

export default {
  components: {
    cascaderDom,
    PointForSelect

  },
  data() {
    return {
      isSpin: false,
      fileUrl: Api.interestedPartiesUserFile,
      selectPointModal: false,
      setCurrentName: {},
                downloadUrl: Api.downloadPTWSchemeFile,
                eTypeList: [],
                eLevelList: [],
                options1: [],

                switchFlag: false,
                form1: {},
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                dataTable: [],
                uploadList: [],
                columns1: [
                    {
                        title: "序号",
                        width: 80,
                        align: "center",
                        fixed: 'left',
                        render: (h, params) => {
                            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
                        }
                    },
                    {
                        title: '应急事件名称',
                        width: 150,
                        align: 'center',
                        key: 'emergencyName',
                    },
                    {
                        title: '报送单位',
                        align: 'center',
                        minWidth: 150,
                        key: 'orgName',
                    },
                    {
                        title: '报送人',
                        width: 150,
                        align: 'center',
                        key: 'userName',
                    },
                    {
                        title: '联系方式',
                        width: 150,
                        align: 'center',
                        key: 'cellPhone',
                    },
                    {
                        title: '发生地点',
                        width: 150,
                        align: 'center',
                        key: 'emergencyLocation',
                    },
                    {
                        title: '坐标名称',
                        width: 150,
                        align: 'center',
                        key: 'axisName',
                    },

                    {
                        title: '事件发生时间',
                        width: 150,
                        align: 'center',
                        key: 'occurDate',
                        sortable: 'custom',
                        render: (h, params) => {
                            return h('div', [
                                (this.formatDate(new Date(params.row.occurDate), 'yyyy-MM-dd'))
                            ]);
                        }
                    },
                    {
                        title: '上报时间',
                        width: 150,
                        align: 'center',
                        key: 'reportDate',
                        sortable: 'custom',
                        render: (h, params) => {
                            return h('div', [
                                (this.formatDate(new Date(params.row.reportDate), 'yyyy-MM-dd'))
                            ]);
                        }
                    },

                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 200,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params, 1);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params, 2);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: 'red'
                                    },
                                    on: {
                                        click: () => {

                                            this.$Modal.confirm({
                                                title: '数据删除',
                                                content: '<p>确定删除该条信息</p>',
                                                okText: '确认',
                                                onOk: () => {
                                                    this.deleteData(params);
                                                },
                                                cancelText: '取消'
                                            });

                                        }
                                    }
                                }, '删除'),
                            ]);
                        }
                    },

                ],
                ruleCustom: {
                    emergencyName: [
                        {required: true, message: '  ', trigger: 'blur'}
                    ],
                    reportOrgId: [
                        {required: true, message: '  ', trigger: 'change'}
                    ],
                    reportorId: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],


                },
                add: false,
                model1: false,
                model2: false,
                buttonLoading: false,
                showdata: {},
                trainEventList: [
                    {
                        lable: "真实事件",
                        value: "1",
                    },
                    {
                        lable: "演练事件",
                        value: "0",
                    },
                ],
                staffOrgId: '',
                staffOrgName: '',
                form1datacopy: {},
                files: [],
                tableHeight: 10,
                loading: false,
                currentOrgId: '',
                currentOrgName: '',
                loading1:false,
            }
        },
        mounted() {
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            this.selectCodingSort();
            this.query();
        },
        methods: {
          selectElevelIds(value) {
            this.form1.eLevels = value.join();
          },
          selecTrainEvent(value) {
            this.form1.trainEvents = value.join();
          },
          getFiles() {
            let url = this.fileUrl + '/' + this.form1datacopy.emergencyId + '/files/info'
            this.$http.get(url).then((res) => {
              if (res.data.result == "success") {
                this.uploadList = res.data.data
              }
            })
          },
          beforeUpload(file) {
            let formData = new FormData();
                formData.append("files", file); // 文件对象
                let url = this.fileUrl + '/' + this.form1datacopy.emergencyId + '/files/info'
                this.$http.post(url, formData).then((res) => {
                    if (res.data.result == "success") {
                        this.$Message.info("文件上传成功")
                        this.getFiles();
                    }
                })
                return false
            },
            downloadFile(guideId, file) {
                let url = this.fileUrl + '/file/' + file.id;
                this.$http.get(url, {
                    responseType: 'blob'      //告诉服务器我们需要的响应格式
                }).then((res) => {

                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = file.fileName //标题
                    aLink.click()
                    document.body.appendChild(aLink)
                })
            },

            remove1(id) {
                console.log(id)
                let url = this.fileUrl + '/file/' + id;
                this.$http.delete(url).then((res) => {
                    this.getFiles()
                })
            },
            getSelectPointData(row) {
                this.form1datacopy.axisX = row.xpos;
                this.form1datacopy.axisY = row.ypos;
                this.form1datacopy.axisName = row.siteName;
                this.selectPointModal = false;
            },
            openPointModal() {
                this.selectPointModal = true;
            },
            setUserName(data) {
                this.form1datacopy.userName = data;
            },
            setUserId(data) {
                this.form1datacopy.reportorId = data[data.length - 1];
            },
            remoteMethod1(query) {
                if (query !== '') {
                    clearTimeout(this.remoteMethod1.timer);
					if(this.form1datacopy.userName != undefined || this.form1datacopy.userName != null){
						query = this.form1datacopy.userName;
					}
                    this.remoteMethod1.timer = setTimeout(() => {
                        this.options1.splice(0, this.options1.length);
                        this.loading1 = true;
                        let data = {
                            userName: query,
                            orgId: sessionStorage('userId').getObject('userId').orgInfo.parentId
                        };
                        this.$http.get(Api.queryUserByUserName, {params: data}).then((res) => {
                            this.loading1 = false;
                            res.data.data.forEach(item => {
                                this.options1.push(item);
                            })

                        }).catch(e => {
                            this.loading1 = false;
                        })
                    }, 200);
                } else {
                    this.options1 = [];
                }
            },
            deleteData(params) {
                let url = Api.deleteEmergencyInfo;
                this.$http.delete(url + '/' + params.row.emergencyId, {params: {}}).then((res) => {
                    if (res.data.status === 200) {
                        this.$Message.success('成功');
                        this.query()
                    } else if (res.data.status === 201) {
                        this.$Message.error(res.data.msg);

                    }
                }).catch(e => {
                    this.$Message.error('请求失败' + e);
                })
            },
            setOrgId(data) {
                this.form1.reportOrgId = data[data.length - 1];
            },
            setOrgName(data) {
                this.form1.orgName = data;
            },
            setCurrentOrgId(data) {
                this.form1datacopy.reportOrgId = data[data.length - 1];
            },
            setCurrentOrgName(data) {
                this.form1datacopy.orgName = data;
            },
            getSelectRows(rows) {
                this.deleteRows = rows;
            },
            batDelete() {

            },
            addInfo() {

                this.options1.push({
                    userId: sessionStorage('userId').getObject('userId').userId,
                    userName: sessionStorage('userId').getObject('userId').userName,
                    orgInfo: {orgName:sessionStorage('userId').getObject('userId').orgInfo.orgName,}
                });

                this.uploadList = [];
                this.form1datacopy = {
                    emergencyId: this.get_uuid(),
                    reportOrgId:sessionStorage('userId').getObject('userId').companyId,
                    orgName:sessionStorage('userId').getObject('userId').companyName,
                    reportDate:new Date()
                };
                this.form1datacopy.reportorId = sessionStorage('userId').getObject('userId').userId;
                this.setCurrentName = {};
                this.currentOrgId = '';
                this.currentOrgName = '';
                this.model1 = true;
                this.add = true;
            },
            get_uuid() {
                let s = [];
                let hexDigits = "0123456789abcdef";
                for (let i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4";
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
                s[8] = s[13] = s[18] = s[23] = "-";

                let uuid = s.join("");
                let reg = new RegExp("-", "g");
                let a = uuid.replace(reg, "");
                console.log(a);
                return a;
            },
            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            handleCancel() {
                this.form1datacopy = {};
				this.options1 = [];
                this.model1 = false;
            },
            selectCodingSort() {
                this.$http.get(Api.queryCodeDetailBySortId + '/TOEE-000001', {params: {}}).then((res) => {
                    this.eTypeList = res.data.data;
                });
                this.$http.get(Api.queryCodeDetailBySortId + '/EL-000001', {params: {}}).then((res) => {
                    this.eLevelList = res.data.data;
                });


            },
            switchQuery(flag) {
                this.switchFlag = flag;
                if (!this.switchFlag) {
                    this.tableHeight = window.innerHeight - 220;
                } else {
                    this.tableHeight = window.innerHeight - 315;
                }
            },
            reset() {
              // this.$refs.trainOrg.resetCurrentOrg();
                this.form1 = {};
                this.staffOrgId = '';
              this.staffOrgName = '';
              this.query();

            },
            query() {
                this.loading = true;
                let data = {
                    startPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    orgId: sessionStorage('userId').getObject('userId').companyId,
                    type:this.$route.query.id
                };
                data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));

                let url = Api.queryEmergencyInfo;
                this.$http.get(url, {params: data}).then((res) => {
                    this.dataTable = res.data.data.data;
                    this.pagedata.total = res.data.data.totalSize;
                    this.loading = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            showData(data, flag) {

                if (flag == 1) {
                    //查看页面

                    this.form1datacopy = data.row;
                    this.getFiles();
                    this.form1datacopy.occurDate = this.formatDate(new Date(this.form1datacopy.occurDate), 'yyyy-MM-dd');
                    this.form1datacopy.reportDate = this.formatDate(new Date(this.form1datacopy.reportDate), 'yyyy-MM-dd');
                    this.model2 = true;
                } else {

                    //修改页面
                    // this.options1.push({
                    //     userId: data.row.reportorId,
                    //     userName: data.row.userName,
                    // });
                    this.add = false;
                    this.form1datacopy = JSON.parse(JSON.stringify(data.row));
					console.log("=========")
					console.log(this.form1datacopy)
                    this.getFiles();
                    this.model1 = true;
                }
            }, formatDate(date, fmt) {
                console.log(date);
                if (!date instanceof Date){

                    return ""
                }
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            async upload() {

            },
            submit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        let userId = sessionStorage('userId').getObject('userId').userId;
                        let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
                        this.buttonLoading = true
                        if (this.form1datacopy.occurDate instanceof Date){
                            this.form1datacopy.occurDate = this.formatDate(new Date(this.form1datacopy.occurDate), 'yyyy-MM-dd');
                        }
                        if (this.form1datacopy.reportDate instanceof Date){
                            this.form1datacopy.reportDate = this.formatDate(new Date(this.form1datacopy.reportDate), 'yyyy-MM-dd');
                        }
                        this.form1datacopy.emeType =  this.$route.query.id;

                        if (this.add) {
                            this.form1datacopy.createUserId = userId;
                            this.form1datacopy.createOrgId = orgId;
                            this.$http.post(Api.saveEmergencyInfo, this.form1datacopy).then((res) => {
                                if (res.data.status === 200) {
                                    this.$Message.success('成功');
                                    this.model1 = false;
                                    this.query()

                                } else if (res.data.status === 201) {
                                    this.$Message.error(res.data.msg);
                                    this.model1 = false;
                                }
                                this.buttonLoading = false
                            }).catch(e => {
                                this.model1 = false;
                                this.query();
                                this.$Message.error("数据获取失败")
                            })
                        } else {
                            this.form1datacopy.updateUserId = userId;
                            this.form1datacopy.updateOrgId = orgId;
                            this.$http.post(Api.updateEmergencyInfo, this.form1datacopy).then((res) => {
                                if (res.data.status === 200) {
                                    this.$Message.success('成功');
                                    this.model1 = false;
                                    this.query()

                                } else if (res.data.status === 201) {
                                    this.$Message.error(res.data.msg);
                                    this.model1 = false;
                                }
                                this.buttonLoading = false
                            }).catch(e => {
                                this.model1 = false;
                                this.query();
                                this.$Message.error("数据获取失败")
                            })
                        }


                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
            querySort({column, key, order}){
              this.form1.key = key;
              this.form1.order = order;
              this.query();
            },
            downloadExcel() {
              let data = {
                startPage: this.pagedata.currentPage,
                size: this.pagedata.pageSize,
                orgId: sessionStorage('userId').getObject('userId').companyId,
                type:this.$route.query.id
              };
              data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
              this.isSpin = true;
              this.$http.get(Api.queryEmergencyInfo + '/export', {
                params:data,
                responseType: 'blob'      //告诉服务器我们需要的响应格式
              }).then((res) => {
                const aLink = document.createElement("a");
                let blob = new Blob([res.data], {
                  type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
                });
                aLink.href = URL.createObjectURL(blob)
                aLink.download = "应急事件信息("+ formatDate(new Date(), "yyyy-MM-dd")+ ").xlsx" //标题
                aLink.click()
                document.body.appendChild(aLink)
                this.isSpin = false;
              })
            },
        },
        watch: {
            "model1": function (qw, er) {
                if (qw && this.model1) {
                    setTimeout(() => {
                        this.$refs.carOrg.setCurrentOrg();

                    }, 100)
                } else {
                    this.$refs.carOrg.resetCurrentOrg();
                }
            },

        },

    }
</script>

<style lang='css' scoped>
    @import '../../../../index.css';

    .demo-spin-icon-load {
      animation: ani-demo-spin 1s linear infinite;
    }

    .demo-upload-list {
      display: inline-block;
      width: 60px;
      height: 60px;
      text-align: center;
      line-height: 60px;
      border: 1px solid transparent;
      border-radius: 4px;
      overflow: hidden;
      background: #fff;
      position: relative;
      box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
      margin-right: 4px;
      margin-top: 4px;
    }

    .demo-upload-list img {
      width: 100%;
      height: 100%;
    }

    .demo-upload-list-cover {
      display: none;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, .6);
    }

    .demo-upload-list:hover .demo-upload-list-cover {
      display: block;
    }

    .demo-upload-list-cover i {
      color: #fff;
      font-size: 20px;
      cursor: pointer;
      margin: 0 2px;
    }

</style>
